package com.zzh.base.utils;

import android.app.Activity;
import android.os.Process;

import java.util.ArrayList;
import java.util.List;

public class ActivityUtil {

    private List<Activity> activityList = new ArrayList<>();
    private static ActivityUtil instance;

    // 单例模式中获取唯一的ExitApplication实例
    public static synchronized ActivityUtil getInstance() {
        if (null == instance) {
            instance = new ActivityUtil();
        }
        return instance;
    }

    // 添加Activity到容器中
    public void addActivity(Activity activity) {
        if (activityList == null)
            activityList = new ArrayList<>();
        activityList.add(activity);
    }

    // 移除Activity
    public void removeActivity(Activity activity) {
        if (activityList != null && activityList.contains(activity))
            activityList.remove(activity);
    }

    // 移除指定activity 及 该activity界面以上的所有界面
    public void removePourSpecifiedActivity (Class cls) {
        int index = -1;
        int allSize = activityList.size();
        for (int i = 0; i < allSize; i++) {
            if (cls.getName().equals(activityList.get(i).getClass().getName())) {
                index = i;
                break;
            }
        }
        for (int i = allSize - 1; i >= index; i--) {
            Activity activity = activityList.get(i);
            if (activity != null) activity.finish();
            activityList.remove(activity);
        }
    }

    public void removePositiveSpecifiedActivity (Class cls) {
        int index = -1;
        int allSize = activityList.size();
        for (int i = allSize - 1; i >= 0; i--) {
            if (cls.getName().equals(activityList.get(i).getClass().getName())) {
                index = i;
                break;
            }
        }
        for (int i = allSize - 1; i >= index; i--) {
            Activity activity = activityList.get(i);
            if (activity != null) activity.finish();
            activityList.remove(activity);
        }
    }

    // 遍历所有Activity并finish
    public void exitSystem() {
        for (Activity activity : activityList) {
            if (activity != null)
                activity.finish();
        }
        // 退出进程
       Process.killProcess(Process.myPid());
       System.exit(0);
    }


}
